import os,re
# -*- coding: utf-8 -*-
import hashlib,socket
from Crypto.Hash.MD4 import new as md4
file='Scrapped Princess - 01.mkv'
'''
hash=hashlib.md5()
file=open('Scrapped Princess - 01.mkv','r')
block_size=9728000
size=0

hex=''
while file:
    try:
        block=file.read(block_size)
        file.seek(block_size+1,1)
        hash.update(block)
        size=block_size+size
        #hex=hex+md4(block).hexdigest()
    except IOError:
        print 'end file'
        break
#ed2k=md4(hex).hexdigest()
#print ed2k    
#hash.update(file)
#size,md5=len(file),hash.hexdigest()
print size,hash.hexdigest()
file.close()
'''

def ed2k_hash_OXIj(file): #Говорим спасибо OXIj за алгоритм
    block_size=9728000

    f=open(file, "rb")
    f.seek(0, 2)
    size = f.tell()
    print size
    f.seek(0, 0)

    chunks = (size // block_size) + 1
    if (size % block_size) == 0: chunks -= 1

    if chunks <= 1:
        return md4(f.read()).hexdigest()

    result_hashes = ""
    for _ in range(0, chunks):
        result_hashes += md4(f.read(block_size)).digest()
    return md4(result_hashes).hexdigest()

print ed2k_hash_OXIj(file)



ED2K_CHUNK_SIZE = 9728000

def filesize(fl):
    pos  = fl.tell()
    fl.seek(0, os.SEEK_END)
    size = fl.tell()
    fl.seek(pos, os.SEEK_SET)
    return size

def eof(fl):
    return filesize(fl) == fl.tell()

def ed2k_hash_Minstrell(filename):
    fl = open(filename, 'rb')
    hashes = []
    chunk = fl.read(ED2K_CHUNK_SIZE)
    if eof(fl):
        return md4(chunk).hexdigest()
    while chunk:
        hashes.append(md4(chunk).digest());
        chunk = fl.read(ED2K_CHUNK_SIZE)
    fl.close()
    return md4(''.join(hashes)).hexdigest()

print ed2k_hash_Minstrell(file)

'''
Оксин набросок хеширования ed2k
import hashlib,socket,os,re
from Crypto.Hash.MD4 import new as md4

def ed2k_hash(path):
    block_size=9728000

    f=open(path, "rb")
    f.seek(0, 2)
    size = f.tell()
    f.seek(0, 0)

    chunks = (size // block_size) + 1
    if (size % block_size) == 0: chunks -= 1

    if chunks == 1:
        return md4(f.read()).hexdigest()

    result_hashes = ""
    for _ in range(0, chunks):
        result_hashes += md4(f.read(block_size)).digest()
    return md4(result_hashes).hexdigest()

print ed2k_hash(sys.argv[1])
'''